package cmsc427.mw5.app;

import java.util.ArrayList;
import java.util.List;


import cmsc427.mw5.*;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ListView;

public class ContactList extends ListActivity {
		
	private ContactAdapter contacts;
	private static MotionReceiver motionReceiver;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		// link up the view items to instance variables
		contacts = new ContactAdapter(this, R.layout.contact_entry, R.id.txtContactEntry);
		
		// add the contacts to the list view 
		populateContactList(getContacts());
		getListView().setAdapter(contacts);
		
		// setings for the list view;
		getContactsAdapter().setSelectedContact(0);
		
		// register broadcast receivers
		motionReceiver = new MotionReceiver(this);
		registerReceiver(motionReceiver, new IntentFilter(BluetoothChat.BROADCAST_MOTION_ACTION));
	}
	
    private void populateContactList(List<Contact> contacts) {
    	
    	// transfer contacts from list to adapter 
    	for(Contact contact : contacts){
    		getContactsAdapter().add(contact);
    	}
    }

    private List<Contact> getContacts()
    {    	
    	List<Contact> contacts;
    	Cursor cursor;
    	
        // generate query to select contacts 
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        // execute query
        cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
        
        // put results in list
        contacts = new ArrayList<Contact>(cursor.getCount());
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
        	contacts.add(new Contact(cursor.getInt(0), cursor.getString(1)));
        	cursor.moveToNext();
        }
        cursor.close(); 
        
        return contacts;
    }
    
    private ContactAdapter getContactsAdapter(){
    	return this.contacts;
    }
    
    @Override
    public ListView getListView(){
    	return super.getListView();
    }
    
    private void placeCall(Contact contact){
    	Intent callIntent = new Intent(Intent.ACTION_CALL);
      	
    	try{
    		callIntent.setData(Uri.parse("tel:" + contact.getPrimaryPhone()));
    		startActivity(callIntent);
    	} catch(ActivityNotFoundException e){
    		
    	} catch(NullPointerException e){
    		
    	}
    }
    
    private static class MotionReceiver extends BroadcastReceiver {

    	private ContactList list;
    	
    	public MotionReceiver(ContactList list) {
    		this.list = list;
    	}
    	
		@Override
		public void onReceive(Context context, Intent intent) {			
			if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_UP)){
				list.getContactsAdapter().setSelectedContact(list.getContactsAdapter().getSelectedPosition() - 1);
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_DOWN)){
				list.getContactsAdapter().setSelectedContact(list.getContactsAdapter().getSelectedPosition() + 1);
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_LEFT)){
				list.placeCall(list.getContactsAdapter().getSelectedContact());	
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_RIGHT)){
				context.unregisterReceiver(motionReceiver);
				list.finish();
			}
		}
    }
}
